package com.seed.test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class ThreadQueryPage {
	
	public static void main(String[] args) throws Exception {
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("config/bean.xml") ;
		ComboPooledDataSource c3p0= (ComboPooledDataSource) ctx.getBean("dataSource") ;
		Connection conn = c3p0.getConnection() ;
		
		PreparedStatement pstmt = conn.prepareStatement("select count(0) from test") ;
		
		ResultSet rs = pstmt.executeQuery() ;
		rs.next() ;
		
		int count = rs.getInt(1) ;
		int ep = 10000 ;
		int tp = 0 ;
		
		if(count % ep == 0) {
			tp = count / ep ;
		} else {
			tp = (count / ep) + 1 ;
		}
		
		for(int i=1; i<=tp; i++) {
			new Thread(new GetData(conn,((i-1)*ep)+1,ep*i),"Thread>>"+i).start() ;
		}
		
	}

}

class GetData implements Runnable{
	
	private Connection conn ;
	
	private int startpage ;
	
	private int endpage ;

	public GetData(Connection conn,int startpage,int endpage) {
		this.conn = conn ;
		this.startpage = startpage ;
		this.endpage = endpage ;
	}
	
	public void run() {
		System.out.println(this.startpage + "==" + this.endpage);
		long startTime=System.currentTimeMillis();   //获取开始时间
		
		try {
			
			String sql = "SELECT * from (SELECT t.*,ROWNUM rn FROM (SELECT * FROM test where ROWNUM <="+this.endpage+") t) ts WHERE ts.rn>="+this.startpage ;
			
			PreparedStatement pstmt = conn.prepareStatement(sql) ;
			
			ResultSet rs = pstmt.executeQuery() ;
			
			while(rs.next()) {
				String n1 = rs.getString(1) ;String n2 = rs.getString(2) ;String n3 = rs.getString(3) ;String n4 = rs.getString(4) ;
				String n5 = rs.getString(5) ;String n6 = rs.getString(6) ;String n7 = rs.getString(7) ;String n8 = rs.getString(8) ;String n9 = rs.getString(9) ;
				
				System.out.println(Thread.currentThread().getName() + " " + n1 +" " + n2 +" " + n3 +" " + n4 +" " + n5 +" " + n6 +" " + n7 +" " + n8 +" " + n9);
			}
			rs.close();
			pstmt.close() ;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		long endTime=System.currentTimeMillis(); //获取结束时间  
		System.out.println("程序运行时间： "+(endTime-startTime)+"ms");  
		System.out.println("程序运行时间： "+(endTime-startTime)/1000+"ms"); 
		
	} 
	
}

















